package com.handong.handserialprogram.module.setting;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.maps.offlinemap.OfflineMapActivity;
import com.google.gson.Gson;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.AppUpdateModel;
import com.handong.handserialprogram.module.base.BackStackFragment;
import com.handong.handserialprogram.module.others.OtherActivity;
import com.handong.handserialprogram.module.qrscan.update.FootUpdateActivity;
import com.handong.handserialprogram.module.setVoice.HintActivity;
import com.handong.handserialprogram.module.setVoice.SetVoiceActivity;
import com.handong.handserialprogram.module.tasklist.TaskListActivity;
import com.handong.handserialprogram.service.DownloadService;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.ViewUtil;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;

import java.util.Timer;
import java.util.TimerTask;

import static android.content.Context.BIND_AUTO_CREATE;

/**
 * Created by userKey on 2017/12/14.
 */

public class SettingFragment extends BackStackFragment {

    public static SettingFragment instance() {
        return new SettingFragment();
    }
    private String TAG="SettingFragment";
    private boolean updatePreventMultipleclicks = false;
    private DownloadService.DownloadBinder mDownloadBinder;
    private ProgressBar mProgressBar;
    private MaterialDialog mProgressDialog;

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mDownloadBinder = (DownloadService.DownloadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mDownloadBinder = null;
        }
    };
    Timer timer;                   //创建一个定时器对象
    public void CheckDownLoadProgress(final long downloadId) {
        timer = new Timer();
        TimerTask task = new TimerTask()        //创建定时器任务对象，必须实现run方法，在该方法中定义用户任务
        {
            @Override
            public void run() {
                int progress = mDownloadBinder.getProgress(downloadId);
                Message msg = new Message();
                msg.what = 1;
                msg.arg1 = progress;
                handler.sendMessage(msg);
            }

        };
        timer.schedule(task, 500, 500);                //启动定时器
    }
    @Override
    protected int getContentViewID() {
        return R.layout.fragment_setting;
    }

    @Override
    protected void initViewByID(View contentView) {
        initHeaderLayout(R.string.nav_system_setting);
        contentView.findViewById(R.id.updateSystemPsd).setOnClickListener(this);
        contentView.findViewById(R.id.navOfflineMap).setOnClickListener(this);
        contentView.findViewById(R.id.footUpdate).setOnClickListener(this);
        contentView.findViewById(R.id.voice_set).setOnClickListener(this);
        contentView.findViewById(R.id.voice_ts_set).setOnClickListener(this);
        contentView.findViewById(R.id.navUpdate).setOnClickListener(this);
        contentView.findViewById(R.id.gps_model).setOnClickListener(this);
        Intent intent = new Intent(getActivity(), DownloadService.class);
//        getActivity().startService(intent);
        getActivity().bindService(intent, mConnection, BIND_AUTO_CREATE);//绑定服务
    }

    @Override
    public void onClick(View v) {
        if (dispatchDoubleClick()){
            return;
        }
        switch (v.getId()) {

            case R.id.navOfflineMap://离线地图
                startActivity(new Intent(getActivity(), OfflineMapActivity.class));
                break;
            case R.id.updateSystemPsd:
                addFrag(ModifySysPsdFragment.newInstance(), R.id.activity_setting);
                break;
            case R.id.footUpdate: //脚环更新
                updateFoot();
                break;
            case R.id.voice_set:
                Intent intent=new Intent(getActivity(), SetVoiceActivity.class);
                startActivity(intent);
                break;
            case R.id.voice_ts_set:
                Intent tsIntent=new Intent(getActivity(), HintActivity.class);
                startActivity(tsIntent);
                break;
            case R.id.navUpdate://版本更新
                updateVersion();
                break;
            case R.id.gps_model:
                Intent gsIntent=new Intent(getActivity(), GPSSettingActivity.class);
                startActivity(gsIntent);
            default:
                super.onClick(v);
        }
    }

    private void updateFoot() {
        Intent intent = new Intent(getActivity(), FootUpdateActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        startActivity(intent);


    }
    /**
     * 更新版本
     */
    private void updateVersion() {
        showLoadDialog("加载中...");
        if (updatePreventMultipleclicks) {
            return;
        }
        updatePreventMultipleclicks = true;
        if (!AsyncHttpUtil.isNetworkConnected(getActivity())) {
            showLoadingFail();
            updatePreventMultipleclicks = false;
            return;
        }
        final Context context = getActivity();
        RequestParams params = new RequestParams("visit", "AppUpdate");
        params.put("AppCode", "2");
        params.put("Version", AppUtil.getVersion(context));
        //params.put(SPUtil.COMPANY_CODE, SPUtil.getStringValue(SPUtil.LOGIN_CODE));
        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                dismissLoadingDialog();
                AppUtil.showShortToast(context, "网络连接异常,请检查配置");
                updatePreventMultipleclicks = false;
            }

            @Override
            public void onRetry(int retryNo) {
                JLog.d(TAG, "onRetry:" + retryNo);
                super.onRetry(retryNo);
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, s);
                dismissLoadingDialog();
                Gson gson = new Gson();
                final AppUpdateModel missionModel = gson.fromJson(s, AppUpdateModel.class);
                if (missionModel.code == 0) {
                    MaterialDialog dialog = new MaterialDialog.Builder(context)
                            .title("版本更新")
                            .content("是否更新到v" + missionModel.Version + "版本？")
                            .canceledOnTouchOutside(false)
                            .positiveText("开始更新")

                            .positiveColorRes(R.color.back_ground_green)
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    dialog.dismiss();
                                    View customView = LayoutInflater.from(context).inflate(R.layout.appupdate_progressbar, null);
                                    //mProgressText=(TextView)customView.findViewById(R.id.down_progress_text);
                                    mProgressBar = (ProgressBar) customView.findViewById(R.id.down_progress);
                                    //Runnable aa=null;
                                    long downloadId = -1;
                                    if (mDownloadBinder != null) {
                                        downloadId = mDownloadBinder.startDownload(missionModel.FileUrl);
                                        //startCheckProgress(downloadId);
                                        CheckDownLoadProgress(downloadId);
                                    }
                                    final long finalDownloadId = downloadId;
                                    mProgressDialog = new MaterialDialog.Builder(context)
                                            .title("正在更新...")
                                            .customView(customView, true)
                                            .positiveText("取消")
                                            .positiveColorRes(R.color.back_ground_green)
                                            .dismissListener(new DialogInterface.OnDismissListener() {
                                                @Override
                                                public void onDismiss(DialogInterface dialog) {
                                                    if (finalDownloadId != -1 && mProgressBar.getProgress() != 100) {
                                                        updatePreventMultipleclicks = false;
                                                        mDownloadBinder.StopDownLoad(finalDownloadId);
                                                        timer.cancel();
                                                    }
                                                }
                                            })
                                            .canceledOnTouchOutside(false)
                                            .build();
                                    ViewUtil.removeHomeKeyListener(mProgressDialog);
                                    //aa.run();
                                }
                            })
                            .negativeColorRes(R.color.dialog_bg)
                            .negativeText(R.string.dialog_negative_text)
                            .onNegative(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    updatePreventMultipleclicks = false;
                                }
                            })
                            .build();
                    ViewUtil.removeHomeKeyListener(dialog);

                    //AppUtil.showShortToast(context, "有新版本，版本号为："+missionModel.AppCode+",地址为："+missionModel.FileUrl);
                } else {
                    AppUtil.showShortToast(context, "当前为最新版本！");
                    updatePreventMultipleclicks = false;
                }
            }
        });
    }
    public void showLoadingFail() {
        dismissLoadingDialog();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mConnection!=null){
            getActivity().unbindService(mConnection);//绑定服务
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    int progress = msg.arg1;
                    mProgressBar.setProgress(progress);//设置进度
                    mProgressDialog.setTitle("正在更新..." + String.valueOf(progress) + "%");
                    if (progress == 100) {
                        mProgressDialog.dismiss();
                        AppUtil.showShortToast(getActivity(), "下载完成！");
                        timer.cancel();
                        updatePreventMultipleclicks = false;

                    }
                    break;
            }
        }
    };
}
